use std::{error::Error, fs, path::PathBuf};

use regex::Regex;
use rfd::FileDialog;
use serde::{Deserialize, Serialize};

pub fn read_text_json(path: &PathBuf) -> Result<PathBuf, Box<dyn std::error::Error>> {
    let content = std::fs::read_to_string(path)?;
    let mut disc_no = 0;
    let disc_regex = Regex::new(r"^(\d+)\.$").expect("disc 正则表达式编译失败");
    let movie_regex = Regex::new(r"^(\d{4})(.*?)(（儿童）)?$").expect("movie 正则表达式编译失败");
    let mut movies = Vec::new();
    for line in content.lines().map(|l| l.trim()).filter(|l| !l.is_empty()) {
        if let Some(x) = disc_number(line, &disc_regex) {
            disc_no = x;
        } else if let Some(x) = movie_regex_captures(disc_no, line, &movie_regex) {
            movies.push(x);
        }else {
            println!("无法解析行: {}", line);
        }
    }
    save_to_json(movies)
}
fn save_to_json(movies: Vec<Movie>) -> Result<PathBuf, Box<dyn Error>> {
    let info = serde_json::to_string_pretty(&movies)?;
    println!("请选择DVD json 文件保存目录");
    let path = FileDialog::new()
        .set_title("保存电影信息")
        .add_filter("JSON Files", &["json"])
        .set_directory(std::env::current_dir()?)
        .save_file()
        .unwrap();
    fs::write(&path, info)?;
    Ok(path)
}
fn disc_number(line: &str, rg: &Regex) -> Option<u32> {
    rg.captures(line)
        .and_then(|cap| cap.get(1))
        .and_then(|m| m.as_str().parse::<u32>().ok())
}
fn movie_regex_captures(disc_no: u32, line: &str, rg: &Regex) -> Option<Movie> {
    rg.captures(line).map(|cap| Movie {
        disc: disc_no,
        year: cap.get(1).unwrap().as_str().to_string(),
        title: cap.get(2).unwrap().as_str().trim().to_string(),
        remark: cap.get(3).map(|m| m.as_str().to_string()),
    })
}
#[derive(Debug, Serialize, Deserialize)]
struct Movie {
    disc: u32,
    title: String,
    year: String,
    remark: Option<String>,
}
